from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel
from typing import Dict, Any
from app.models.tb_bbe_patient_info import TBBBEPatientInfo
from app.utils.database import create_connection
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/patient-data", tags=["patient_data"])

class PatientDataRequest(BaseModel):
    """患者数据请求模型"""
    data: Dict[str, Any]

# 不进行字段名映射，直接使用原始字段名
def use_original_field_names(data: Dict[str, Any]) -> Dict[str, Any]:
    """
    直接使用原始字段名，不进行映射
    """
    return data

@router.post("/", status_code=status.HTTP_201_CREATED)
async def save_patient_data(request: PatientDataRequest):
    """
    保存患者数据到数据库
    """
    try:
        # 创建数据库连接
        db = create_connection()
        cursor = db.cursor()
        
                # 不进行字段名映射，直接使用原始字段名
        mapped_data = use_original_field_names(request.data)
        # 打印
        print(mapped_data)
        
        # 构造INSERT语句
        columns = []
        values = []
        placeholders = []
        
        for key, value in mapped_data.items():
            columns.append(key)
            values.append(value)
            placeholders.append("%s")
        
        # 特别处理id字段，确保它被包含在内
        if 'id' not in mapped_data and 'ID' not in mapped_data:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="缺少必需的'id'字段"
            )
        
        # 构建SQL语句
        sql = f"INSERT INTO tb_bbe_patient_info ({', '.join(columns)}) VALUES ({', '.join(placeholders)})"
        
        # 执行插入操作
        cursor.execute(sql, values)
        db.commit()
        
        inserted_id = mapped_data.get('id') or mapped_data.get('ID')
        logger.info(f"患者数据保存成功，ID: {inserted_id}")
        
        # 关闭游标和连接
        cursor.close()
        db.close()
        
        return {
            "success": True,
            "message": "患者数据保存成功",
            "data": {
                "id": inserted_id
            }
        }
    except Exception as e:
        logger.error(f"保存患者数据时出错: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"保存患者数据时出错: {str(e)}"
        )